# -*- coding: utf8 -*-
# © 2011 Coet@cawiki
#wikimedia.py
import time
from core.ircfuncs import *
from core.ircvars import ch
from util.functions import is_ip

#########

#no incloc les vocals que dificílment poden ajuntar-se amb un tecleig a l'atzar i trec la y per donar molts falsos positius
#ja que en altres ortografies té la funció de vocal, podria passar amb la w en alguns iw de llengües celtes.
#trec 'r' i 's' per trobar-se en molts grups consonàntics
blacklist=[
	#insercions botons javascript
	ur'\'{2}text en cursiva\'{2}|\'{3}text en negreta\'{3}|\[\[títol de l\'enllaç\]\]|\[http://www\.exemple\.cat títol de l\'enllaç\]|== títol secció ==|\[\[media:exemple\.ogg\]\]|<nowiki>inseriu el text sense format ací</nowiki>|<math>inseriu una fórmula ací</math>|\[\[imatge:exemple\.png\]\]|<s></s>|# element 1\n# element 2\n# element 3|<!---->|<gallery>\s+image:vista-openbsd\.png\|llegenda\s+image:amule\.png\|llegenda\s+image:cyberduck icon\.png\|llegenda\s+</gallery>|#redirect \[\[article destí\]\]',
	#caracters repetits, email, emoticones
	r'!!!+',
	ur'[bcdfghjklmnpqtvwxzçñ]{5,}',
	ur'[aeiouy]{5,}', ur'[rs]{5,}',
	ur'.+@.+\..{1,3}', ur":\)|:$|\bxd\b|:'\(",
	#a, b, c
	ur'ag[áa]rrame', ur'asquer[oó]ss?(?:os?)?', 'boludo', ur'[kc]abr[óo]n?[ae]?s?',
	ur'\bcaca(?:lane?s)?\b', ur'\bcag(?:ar?|ue(?:ta)?|[óo]n?[ae]?s?)\b', 'carajo',
	ur'co[bv]ard[ae]?', ur'co(?:llons|j[óo]nes)', 'concha', ur'co(?:ñ|ny)[oa]?',
	ur'\b(?:ch|x)ulos?', ur'(?:llepa|chupa|\b)culo?s?\b', ur'(?:ch|x)[úu]pa[mt]e',
	ur'cutres?', ur"em di(c|uen)|me llamo",
	#e, f, g
	ur'est[uú]pido', 'forro', ur'feixist(?:a|es?)|fascistas?', r'\bfot(?:re|[ie]n)\b',
	r'\bfoll(?:[ae][ns]?|ar)\b', r'friki', r'gilipoll([ae]s|ez)', ur'\bguay\b',
	ur'\b(?:gü|wh?|hu)ey\b',
	#h, i, j
	ur'hij[oa]s? de [st]u', ur'\b(?:hi(?:de|jo|ja)?|ja|jo)putas?\b', ur"\bhola\b",
	ur'\bh?[òo]sti[ae]s?\b', ur'jod(?:[ae][ns]?|er)',
	#k,l,m,n
	ur'\bmalpari(t|d?[aeo])s?\b', ur'mam[oó]na?', ur'mari(?:ca|c[oó]n|qu(?:es|ita))',
	ur'mi?erda', ur'\bnardos?\b',
	#o,p,q,r
	ur'\bpen(?:es?|is)\b', ur'\bpoll(?:as?|[oó]n|es)\b', ur'\bput(ad)?[aeo]s?\b',
	ur'putej?ar', 'putamadre', ur'pu[ñn]eta[sz]o', ur'paj(?:ill)?ero', 'pendej',
	ur'pij[oa]s?', ur'\b(ce)?porros?\b',
	#s, t, u v, w, x, y z
	'suda[kc]a', 'travesti', ur"\bt'?[ae]stim[oue]\b|te ?vull|te ?quiero",
	ur'tont[aoe]s?', ur'tranca', ur'\btrola[zs]o', ur'tu (madre|vieja)',
	ur'\buu+isme\b|labernisme', 'verga',
	#frases i anglés
	ur'vi[xs]ca lo regne de val[eèé]ncia', ur'(viva|arriba) españa', ur'zorra',
	ur"\b([fs]uck|cock|deck|pussy|cunt|whore)\b"
]

whitelist=[
	ur'\{\{copyvio', ur'\{\{millorar', ur'\{\{falten referències',
	ur'\{\{cal citació', ur'{\{neutralitat\}\}'
] #ur'\{\{FR\}\}',#ur'\{\{contextualitzar', ur'\{\{irrellevant', ur'\{\{sense ?rellev[àa]ncia']

RE_IRC_RC = {
	#09.06.2009
	#ordre de les marques: !NMB http://ca.wikipedia.org/wiki/?oldid=3817722&rcid=3822888
	#modificació de pàgines *M?* grups: page, marques, menor, url, diff, oldid, rcid, usuari, diffsize, summary
	"edit":
		re.compile(ur'\x0314\[\[\x0307(?P<page>.*?)\x0314\]\]\x034 (?P<flags>(?P<patrol>!?)(?P<minor>M?)(?P<bot>B?))\x0310 \x0302(?P<url>http://.*?/w/index\.php\?diff=(?P<diff>\d*)&oldid=(?P<oldid>\d*)(&rcid=(?P<rcid>\d*))?)\x03 \x035\*\x03 \x0303(?P<user>.*?)\x03 \x035\*\x03 \(\x02?(?P<diffsize>[+-]\d*)\x02?\) \x0310(?P<summary>.*)\x03'), # changed page, with or without rcid, with or without comment
	#pàgina nova amb rcid *M?N* grups: page, marques, menor, nou, url (.../w/index.php?title=...) , rcid, usuari, diffsize, summary
	"new":
		re.compile(ur'\x0314\[\[\x0307(?P<page>.*?)\x0314\]\]\x034 (?P<flags>(?P<patrol>!?)(?P<new>N)(?P<minor>M?)(?P<bot>B?))\x0310 \x0302(?P<url>http://.*?/w/index\.php\?oldid=(?P<oldid>\d*)&rcid=(?P<rcid>\d*))\x03 \x035\*\x03 \x0303(?P<user>.*?)\x03 \x035\*\x03 \(\x02?(?P<diffsize>[+-]\d*)\x02?\) \x0310(?P<summary>.*)\x03'), # new page with rcid
	#Log:newusers *create* grups: page, marques=create, usuari
	"create":
		re.compile(ur'\x0314\[\[\x0307(?P<page>.*?)\x0314\]\]\x034 (?P<flags>create)\x0310 \x0302\x03 \x035\*\x03 \x0303(?P<user>.*?)\x03 \x035\*\x03  \x0310.*\x03'), # new users *create*
	#Log:newusres *create2* grups: page, marques=create, usuari, element1 (=usuari nou)
	"create2":
		re.compile(ur'\x0314\[\[\x0307(?P<page>.*?)\x0314\]\]\x034 (?P<flags>create2)\x0310 \x0302\x03 \x035\*\x03 \x0303(?P<user>.*?)\x03 \x035\*\x03  \x0310.*\x0302.*:(?P<element1>.*)\x0310\x03'), # new users *create*
	#Log:move amb summary (cada llengua utilitza una cadena diferent, adaptat a cawiki) grups: log, marques=move_redir, usuari, element1, element2, summary
	"move":
		re.compile(ur'\x0314\[\[\x0307(?P<page>.*?)\x0314\]\]\x034 (?P<flags>move(?:_redir)?)\x0310 \x0302\x03 \x035\*\x03 \x0303(?P<user>.*?)\x03 \x035\*\x03  \x0310(?P<element1>.*?) mogut a (?P<element2>.*?)(?: per redirecció)?(?::(?P<summary>.*?) )?\x03'), # move and move_redir with or without summary
	#Log:upload *upload* grups: page, marques, usuari, element1, summary
	"upload":
		re.compile(ur'\x0314\[\[\x0307(?P<page>.*?)\x0314\]\]\x034 (?P<flags>upload)\x0310 \x0302\x03 \x035\*\x03 \x0303(?P<user>.*?)\x03 \x035\*\x03  \x0310.*\x0302(?P<element1>Fitxer:.*?)\x0310\]\]..?(?P<summary>.*)\x03?'),
	#Log:upload *overwrite* grups: page, usuari, element1, summary
	"overwrite":
		re.compile(ur'\x0314\[\[\x0307(?P<page>.*?)\x0314\]\]\x034 (?P<flags>overwrite)\x0310 \x0302\x03 \x035\*\x03 \x0303(?P<user>.*?)\x03 \x035\*\x03  \x0310.*\x0302(?P<element1>Fitxer:.*?)\x0310\]\].: (?P<summary>.*)'),
	#Log:delete *delete* *restore* grups: page, marques, usuari, element1, summary
	#                      "\x0314\[\[\x0307(?P<page>.*?)\x0314\]\]\x034 (?P<flags>delete|restore)\x0310 \x0302\x03 \x035\*\x03 \x0303(?P<user>.*?)\x03 \x035\*\x03  \x0310.*? «\[\[\x0302(?P<element1>.*?)\x0310\]\]»: (?P<summary>.*?)\x03"
	"delete":
		re.compile(ur'\x0314\[\[\x0307(?P<page>.*?)\x0314\]\]\x034 (?P<flags>delete|restore)\x0310 \x0302\x03 \x035\*\x03 \x0303(?P<user>.*?)\x03 \x035\*\x03  \x0310.*? «\[\[\x0302(?P<element1>.*?)\x0310\]\]»: (?P<summary>.*?)\x03'), # delete with summary and restore (always with summary)
	#Log:block *block* *unblock* grups: page, marques, usuari, blocat, durada, summary
	"block":
		re.compile(ur"\x0314\[\[\x0307(?P<page>.*?)\x0314\]\]\x034 (?P<flags>block)\x0310 \x0302\x03 \x035\*\x03 \x0303(?P<user>.*?)\x03 \x035\*\x03  \x0310.*? \[\[\x0302Usuari:(?P<blocked>.*?)\x0310\]\].*? de: (?P<while>.*?);? \((?P<options>.*?)\)(?:: (?P<summary>.*))?\x03"), # block with summary
	#Log:block *unblock* grups: page, marques, usuari, blocat, durada, summary
	"unblock":
		re.compile(ur'\x0314\[\[\x0307(?P<page>.*?)\x0314\]\]\x034 (?P<flags>unblock)\x0310 \x0302\x03 \x035\*\x03 \x0303(?P<user>.*?)\x03 \x035\*\x03  \x0310.*?\x0302.*?:(?P<blocked>.*?)\x0310: (?P<summary>.*)\x03'), # unblock with summary
	#Log:protect *protect* *modify* grups: page, marques, usuari, element1, summary
	"protect":
		re.compile(ur'\x0314\[\[\x0307(?P<page>.*?)\x0314\]\]\x034 (?P<flags>protect|modify)\x0310 \x0302\x03 \x035\*\x03 \x0303(?P<user>.*?)\x03 \x035\*\x03  \x0310.*?\x0302(?P<element1>.*?)\x0310.*?(?P<summary>.*?)\x03'),
	#Log:protect *unprotect* grups: page, marques, usuari, element1, summary
	"unprotect":
		re.compile(ur'\x0314\[\[\x0307(?P<page>.*?)\x0314\]\]\x034 (?P<flags>unprotect)\x0310 \x0302\x03 \x035\*\x03 \x0303(?P<user>.*?)\x03 \x035\*\x03  \x0310.*?\x0302(?P<element1>.*?)\x0310\]\](?P<summary>.*?)\x03'),
	#Log:patrol *patrol* grups: page, flags, user, element1
	#10.06.09              '\x0314\[\[\x0307(?P<page>.*?)\x0314\]\]\x034 (?P<flags>patrol)\x0310 \x0302\x03 \x035\*\x03 \x0303(?P<user>.*?)\x03 \x035\*\x03  \x0310.*?\x0302(?P<element1>.*?)\x0310.*?\x03'
	"patrol":
		re.compile(ur'\x0314\[\[\x0307(?P<page>.*?)\x0314\]\]\x034 (?P<flags>patrol)\x0310 \x0302\x03 \x035\*\x03 \x0303(?P<user>.*?)\x03 \x035\*\x03  \x0310.*?\x0302(?P<element1>.*?)\x0310\]\].*?\x03'),
	#MISSING: renameuser
}
regexps = [
	re.compile(r'\x0314\[\[\x0307(?P<title>.*?)\x0314\]\]\x034 (?P<flags>.*?)\x0310 \x0302http:\/\/.*?\/w\/index\.php\?title=.*?&diff=(?P<diff>[0-9]*)&oldid=(?P<oldid>[0-9]*)(&rcid=(?P<rcid>[0-9]*))?\x03 \x035\*\x03 \x0303(?P<user>.*?)\x03 \x035\*\x03 \(\x02?(?P<diffsize>[+-][0-9]*)\x02?\) \x0310(?P<comment>.*)\x03'),
	re.compile(r'\x0314\[\[\x0307(?P<title>.*?)\x0314\]\]\x034 (?P<flags>.*?N)\x0310 \x0302http:\/\/.*?\/w\/index\.php\?title=.*?&rcid=(?P<rcid>[0-9]*)\x03 \x035\*\x03 \x0303(?P<user>.*?)\x03 \x035\*\x03 \(\x02?(?P<diffsize>[+-][0-9]*)\x02?\) \x0310(?P<comment>.*)\x03'),
	re.compile(r'\x0314\[\[\x0307(?P<title>.*?)\x0314\]\]\x034 (?P<flags>.*?N)\x0310 \x0302http:\/\/.*?\/wiki/.*?\x03 \x035\*\x03 \x0303(?P<user>.*?)\x03 \x035\*\x03 \(\x02?(?P<diffsize>[+-][0-9]*)\x02?\) \x0310(?P<comment>.*)\x03'),
	re.compile(r'\x0314\[\[\x0307(?P<title>.*?)\x0314\]\]\x034 (?P<flags>.*?)\x0310 \x0302\x03 \x035\*\x03 \x0303(?P<user>.*?)\x03 \x035\*\x03  \x0310(?P<comment>.*)\x03')
]

#
#functions to get user editions
#
def clean_inactive(g):
	temp_dict=g.users.copy()
	for usr in temp_dict:
		#als sis mesos sense editar, retirem l'usuari
		if time.time() - g.users[usr][1] > 15552000 and g.users[usr][3] == "":
			print u"%r: eliminat > sis mesos inactiu" % usr
			del g.users[usr]
		#si l'usuari du una setmana sense editar i menys de 50 edicions, l'esborrem
		if time.time() - g.users[usr][1]>604800 and g.users[usr][2] < 50 and g.users[usr][3] == "principiant":
			print u"%r: eliminat > 1 setmana inactiu amb < 50 eds" % usr
			del g.users[usr]
	acc_deleted = len(g.users)-len(temp_dict)
	g.users.save()
	temp_dict=g.IPs.copy()
	for ip in temp_dict:
		if time.time() - g.IPs[ip][1] > 604800 and (g.IPs[ip][3] == "" or g.IPs[ip][4] == 0):
			print u"%s: IP eliminada!" % ip
			del g.IPs[ip]
	ip_deleted = len(g.IPs)-len(temp_dict)
	del temp_dict
	g.IPs.save()
	print "users %i / %i (%i)" % ( len(g.users), len(g.users) - acc_deleted, acc_deleted)
	print "ips %i / %i (%i)" % ( len(g.IPs), len(g.IPs) - ip_deleted, ip_deleted)

def register_user(user, log, flags="e"):
	edits = user.info('editcount')
	user_str = user.nick().replace(" ", "_")
	#users: nick: [register_timestamp, lastedit_timestamp, number_of_edits, comment]
	#ips: xx.xx.xx.xx: [register_timestamp, lastedit_timestamp, number_of_edits, comment, number_of_blocks]
	if not user.is_anon(): #Com no és una IP, el registrem, si no està ja registrat
		if not log.has_key(user_str): # No està registrat
			f = user_flag(user, edits)
			log[user_str] = [time.time(), time.time(), edits, f, 0]
		else: # Si està registrat
			log[user_str][1] = int(time.time())
			if flags.strip("!") in ("M", "N", "NM", "e"):
				log[user_str][2]+=1
	else:
		if not log.has_key(user_str):
			if edits < 20: f = "NOVELL"
			elif edits < 50: f = "principiant"
			elif edits < 100: f = u"avançat"
			elif edits < 200: f = "avesat"
			elif edits < 500: f = "consolidat"
			elif edits < 1000: f = "entregat"
			elif edits >= 1000: f = u"veterà"
			log[user_str]=[time.time(), time.time(), edits, "", 0]
		else: # Si està registrat
			log[user_str][1] = time.time()
			if flags.strip("!") in ("M", "N", "NM", "e"):
				log[user_str][2]+=1
	log.save()

def last_contrib(usr, log):
	usr=usr.replace(" ", "_")
	try:
		c = log[usr][1]
	except KeyError:
			c = "<usuari no trobat>"
	return c

def get_numeds(usr, log):
	usr = usr.replace(" ","_")
	try:
		return log[usr][2]
	except KeyError:
		#-1 = ip sense edicions; -2 = usuari sense edicions
		return -3

#
# formatting output messages
#
def user_flag(user, edits):
	if user.is_anon():
		flag=u"ANÒNIM"
	elif edits < 20:
		flag="NOVELL"
	elif edits < 50:
		flag="principiant"
	elif edits < 100:
		flag=u"avançat"
	elif edits < 200:
		flag="avesat"
	elif edits < 500:
		flag="consolidat"
	elif edits < 1000:
		flag="entregat"
	elif edits < 2000:
		flag = "veterà"
	else:
		flag = "llegenda"
	return flag

class _Format:
	"""Many templates for formatting.
	"""
	def __init__(self):
		pass

	def action(self, value):
		return "%s%s%s" % (ch.red() + ch.bold(), value, ch.normal())

	def dsize(self, value):
		return "%s(%s)%s" % (ch.red(), value, ch.normal())

	def link(self, value):
		return "%s " % value

	def line(self, *params):
		return "%s %s." % (" ".join(params[:-1]), params[-1]) if len(params)>1 else "%s." % params[0]

	def loggeduser(self, value):
		return u"%s%s%s" % (ch.blue(), value, ch.normal())

	def match(self, value):
		return "[%s]" % value

	def mov_f(self, value):
		return "[[%s%s%s]]" % (ch.purple() + ch.bold(), value, ch.normal())

	def mov_t(self, value):
		return "[[%s%s%s]]" % (ch.magenta(), value, ch.normal())

	def obs(self, value):
		return "%s%s%s" % (ch.orange(), value, ch.normal())

	def number(self, value):
		return "%s%s%s" % (ch.teal(), value, ch.normal())

	def page(self, value):
		return "[[%s%s%s]]" % (ch.blue(), value, ch.normal())

	def special(self, value):
		return "%s[%s]%s" % (ch.yellow() + ch.bold() + ch.background() + ch.light_gray(), value, ch.normal())

	def sugg(self, value):
		return "%s[%s]%s" % (ch.blue() + ch.bold(), value, ch.normal())

	def summ(self, value):
		value = slice_summ(value)
		return "%s(%s)%s" % (ch.orange(), value, ch.normal())

	def sysop(self, value) :
		return "%s%s%s" % (ch.bold() + ch.dark_green() + ch.underline(), value, ch.normal())

	def topic(self, value):
		return "%s[%s]%s" % (ch.red() + ch.bold(), value, ch.normal())

	def user(self, value) :
		return "%s%s%s" % (ch.dark_green() + ch.underline(), value, ch.normal())

	def userflag(self, value):
		return "%s[%s]%s" % (ch.yellow(), value, ch.normal())

	def vandal(self, value):
		value = slice_summ(value)
		return "%s%s%s" % (ch.red(), value, ch.normal())
F = _Format()

def slice_summ(summ): #slice_summ
	if not summ: return ""
	summ = summ.replace("[[Usuari:Pasqual/viquiestris|Viquiestris]]","Viquiestris")
	summ = summ.replace(u"Pàgina nova, amb el contingut:","Contingut:")
	if len(summ) > 150:
		summ = u"%s…" % summ[:147]
	return summ
